package com.wuye.web.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuye.web.system.entity.SysRole;
import com.wuye.web.system.entity.SysRoleParam;
import com.wuye.web.system.mapper.SysRoleMapper;
import com.wuye.web.system.mapper.UserRoleMapper;
import com.wuye.web.system.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author 孤筏
 * @since 2023-07-26
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public IPage<SysRole> listRoles(SysRoleParam sysRoleParam) {
        //创建分页对象
        IPage<SysRole> page = new Page<>(sysRoleParam.getCurrentPage(),sysRoleParam.getPageSize());
        //创建查询条件
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(sysRoleParam.getRoleName())){
            lambdaQueryWrapper.like(SysRole::getRoleName,sysRoleParam.getRoleName());
        }

        return this.baseMapper.selectPage(page,lambdaQueryWrapper);
    }

    @Override
    public List<SysRole> checkRoles(Integer userId) {
        //查询sys_role表中的所有角色信息
        List<SysRole> roleList = this.baseMapper.selectList(null);
        //从sys_user_role表中查询该用户的所有角色的id
        List<Integer> sysUserRoles = userRoleMapper.selectRoleIds(userId);

        List<SysRole> result = roleList.stream().map(role -> {
            if (sysUserRoles.contains(role.getRoleId()))
                role.setChecked(true);
            return role;
        }).collect(Collectors.toList());

        return result;
    }
}
